package ch.zbw.sysventory.server.control;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import ch.zbw.sysventory.server.model.ScanConfiguration;
import ch.zbw.sysventory.server.service.ScanConfigurationService;

@Component
@Controller
public class ScanConfigurationController {

	@Autowired
	private ScanConfigurationService scanConfigurationService;

	@Autowired
	private Validator scanConfigurationValidator;

	@RequestMapping(value = "/scanconfiguration", method = RequestMethod.GET)
	public ModelAndView showUser(Model model) {
		model.addAttribute("configuration", this.scanConfigurationService.getConfiguration());
		return new ModelAndView("configuration");
	}

	@RequestMapping(value = "/scanconfiguration", method = RequestMethod.POST)
	public ModelAndView saveUser(Model model, @ModelAttribute("configuration") ScanConfiguration configuration, BindingResult result) throws Exception {

		this.scanConfigurationValidator.validate(configuration, result);
		if (!result.hasErrors()) {
			this.scanConfigurationService.update(configuration);
			model.addAttribute("saved", "1");
		} else {
			configuration = this.scanConfigurationService.getConfiguration();
		}
		return new ModelAndView("configuration");
	}

}
